"use strict"

const run = require('./run').await_for
const _ = require('lodash/fp')
const fetch = require('node-fetch')
const cheerio = require('cheerio')
const e = raw => raw.replace(/([\\'"])/gm, '\\$1')
const e_url = raw => raw//.replace(/(https:\/\/)/gm, 'http://')
const opt = {
    timeout: 5000,
}

const iterator = function* (cate) {
    //YY url格式： http://www.yy.com/more/page.action?biz=${cate.biz}&subBiz=idx&page=${page}&moduleId=${cate.id}

    const url = `http://www.yy.com/more/page.action?subBiz=idx`;
    let page = 1
    let done = false

    const format = result => {
        const data = result.data.data
        if (data.length === 0) return done = true

        return data
            .filter(_ => _.type === 4 && _.name)
            .map(i => ({
                live_id: 15,
                name: e(i.name),
                room_name: e(i.desc),
                room_id: i.sid,
                online: i.users,
                id: 'yy_' + i.sid,
                url: i.liveUrl,
                cover: e_url(i.thumb),
                avatar: i.avatar ? i.avatar : e_url(i.thumb),
                category_id: cate.id,
                category_name: cate.name,
                category_url: cate.url,
            }))
    }

    while (!done && page < 50)
        yield fetch(`${url}&biz=${cate.biz}&page=${page++}&moduleId=${cate.id}`, opt)
            .then(_ => _.json())
            .then(format)
}

module.exports = {
    run: () => {
        fetch("http://www.zhangyu.tv/channel/all")
            .then(_=>_.text())
            .then(html => {
                cheerio.load(html)('ul.ui-tab li a')
            })

        return Promise.all(cates.map(cate => run(iterator(cate)))).then(_.flattenDeep).then(_.uniqBy('id'))
    }
}